package com.express.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.net.URL;

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传
     *
     * @param bytes      文件字节数组
     * @param objectName 上传文件的对象名称
     * @return 文件的访问路径
     */
    public String upload(byte[] bytes, String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObject请求并上传文件
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            log.error("OSSException: 请求已到达OSS，但被拒绝，错误信息：{}", oe.getErrorMessage());
            log.error("错误代码：{}", oe.getErrorCode());
            log.error("请求ID：{}", oe.getRequestId());
            log.error("主机ID：{}", oe.getHostId());
            throw new RuntimeException("OSS上传失败，错误信息：" + oe.getErrorMessage(), oe);
        } catch (ClientException ce) {
            log.error("ClientException: 客户端遇到严重问题，无法与OSS通信，错误信息：{}", ce.getMessage());
            throw new RuntimeException("上传失败，网络问题或客户端错误", ce);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        // 构建文件的URL
        try {
            URL url = new URL("https", bucketName + "." + endpoint, "/" + objectName);
            String fileUrl = url.toString();

            log.info("文件上传成功，文件访问路径：{}", fileUrl);
            return fileUrl;
        } catch (Exception e) {
            log.error("构建文件访问路径失败: {}", e.getMessage());
            throw new RuntimeException("构建文件访问路径失败", e);
        }
    }
}
